<script setup>
import axios from 'axios'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import videoView from '@/views/player.vue'
import { useStore } from 'vuex'
import { useRouter } from "vue-router";
import { printInfo } from '@/util/log';
import { computed, onMounted } from 'vue'
const store = useStore()
const router = useRouter()
const isLoggedIn = computed(() => !!store.state.Authorization)

const videoData = ref([])
const progress = ref(0)

async function getVideoList() {
  try {
    const result = await axios.get(import.meta.env.VITE_API_HOST + '/db.php?dbType=getAll')
    videoData.value = result.data.data
    console.log(videoData.value)
  } catch(error) {
    console.log(error)
  }
}
getVideoList()

function delVideo(id) {
  axios.get(import.meta.env.VITE_API_HOST + '/db.php?dbType=delItem&id=' + id)
  .then(function (response) {
    console.log(response)
    if (response.data.code == 200) {
      ElMessage.success('操作成功')
      getVideoList()
    } else {
      ElMessage.error('操作失败')
    }
  })
  .catch(function (error) {
    console.log(error)
    ElMessage.error('操作失败')
  })
}
const dialogVisible = ref(false)

import {
 UploadFilled,
 Plus
} from '@element-plus/icons-vue'

function handleChange(file, fileList) {
  const accept = "mp4"
  const isFileTypeIf = accept.split(',').includes(`${file.name.split('.').pop().toLowerCase()}`)
  if (!isFileTypeIf) {
    ElMessage.error("文件格式错误")
  }
  console.log(isFileTypeIf, file)
  return isFileTypeIf
}

function handleSuccess(response, file, fileList) {
  if (response.error != null) {
    ElMessage.error(response.error)
  }
  if (response[0].status == 'success') {
    ElMessage.success("上传成功")
  } else {
    ElMessage.error("上传失败")
  }
}

function handleError(err, file, fileList) {
  ElMessage.error("上传错误")
}

async function upload(file, fileList) {
  const formData = new FormData();
  formData.append("file", file.file);
  progress.value = 0;
  try {
    const result = await axios.post(import.meta.env.VITE_SERVER_HOST + ':3000/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        console.log('Progress event:', progressEvent);
        progress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        console.log(`上传进度: ${progress.value}%`);
      }
    })
    input6.value = '/dmcy' + result.data.data.url
    return result.data
  }catch (e) {
    console.log(e)
    ElMessage.error("上传错误")
  }
}

async function upload1(file, fileList) {
  const formData = new FormData();
  formData.append("file", file.file);
  progress.value = 0;
  try {
    const result = await axios.post(import.meta.env.VITE_SERVER_HOST + ':3000/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        console.log('Progress event:', progressEvent);
        progress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        console.log(`上传进度: ${progress.value}%`);
      }
    })
    input8.value = '/dmcy' + result.data.data.url
    console.log(`上传进度: ${progress.value}%`);
    return result.data
  }catch (e) {
    console.log(e)
    ElMessage.error("上传错误")
  }
}

async function uploadfm(file, fileList) {
  const formData = new FormData();
  formData.append("file[]", file.file);
  try {
    const result = await axios.post(import.meta.env.VITE_API_HOST + '/uploadbanner.php', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    input5.value = './' + result.data[0].path
    return result.data
  }catch (e) {
    console.log(e)
    ElMessage.error("上传错误")
  }
}

function beforeAvatarUpload(file) {
  const accept = "png,jpg,jpeg"
  const isFileTypeIf = accept.split(',').includes(`${file.name.split('.').pop().toLowerCase()}`)
  if (!isFileTypeIf) {
    ElMessage.error("文件格式错误")
  }
  console.log(isFileTypeIf, file)
  return isFileTypeIf
}

const imageUrl = ref('')

const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}
const input4 = ref('')
const input5 = ref('')
const input6 = ref('')
const input7 = ref('第一集')
const input8 = ref('')
const id = ref('')
const jisList = ref([])

const radio1 = ref('2')
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)
const VideoView = ref(null)
function handleClose() {
  dialogVisible1.value = false
  console.log(VideoView.value)
  VideoView.value.player.pause()
}
const video = ref('')
function playVideo(url) {
  video.value = url
  dialogVisible1.value = true
}
async function submit() {
  const jise = ref(false)
  if (radio1.value == 1) {
    jise.value = true
  } else {
    jise.value = false
  }
  const url1 = `${import.meta.env.VITE_API_HOST}/db.php?dbType=update&id=${id.value}&upd=title&nr=${input4.value}`
  const url2 = `${import.meta.env.VITE_API_HOST}/db.php?dbType=update&id=${id.value}&upd=cover&nr=${input5.value}`
  const url3 = `${import.meta.env.VITE_API_HOST}/db.php?dbType=update&id=${id.value}&upd=video&nr=${input6.value}`
  const url4 = `${import.meta.env.VITE_API_HOST}/db.php?dbType=update&id=${id.value}&upd=jis&nr=${jise.value}`
  try {
    const result1 = await axios.post(url1)
    const result2 = await axios.post(url2)
    const result3 = await axios.post(url3)
    const result4 = await axios.get(url4)
    if (result1.data.code === 200 && result2.data.code === 200 && result3.data.code === 200 && result4.data.code === 200) {
      ElMessage({
        message: '修改成功',
        type: 'success'
      })
      getVideoList()
    } else {
      ElMessage({
        message: '修改失败',
        type: 'error'
      })
    }
  } catch (error) {
    console.log(error)
  }
}
const id1 = ref('')
async function submit1() {
  try {
    const result = await axios.post(import.meta.env.VITE_API_HOST + '/db.php?dbType=addJIS&title=' + input7.value + '&video=' + input8.value + '&id=' + id1.value)
    if (result.data.code === 200) {
      ElMessage({
        message: '添加成功',
        type: 'success'
      })
      getVideoList()
      getJISList()
    } else {
      ElMessage({
        message: '添加失败',
        type: 'error'
      })
    }
  } catch (error) {
    console.log(error)
  }
}

function getJISList() {
  try {
    const result = axios.get(import.meta.env.VITE_API_HOST + '/db.php?dbType=getID&id=' + id1.value)
    result.then(function (response) {
      jisList.value = response.data.list
    })
  } catch (error) {
    console.log(error)
  }
}

async function delJis (uid) {
  try {
    const result = await axios.post(import.meta.env.VITE_API_HOST + '/db.php?dbType=delJIS&id=' + id1.value + '&jisID=' + uid)
    if (result.data.code === 200) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      getJISList()
    } else {
      ElMessage({
        message: '删除失败',
      })
    }
  } catch (error) {
    console.log(error)
  }
}

onMounted(() => {
  if (isLoggedIn.value) {
    printInfo({ title: "登录成功", text: "欢迎回来", type: "success", plain: true });
  } else {
    printInfo({ title: "登录失败", text: "请检查你的登录信息", type: "error", plain: true });
    router.push("/login");
    store.dispatch('logout');
  }
})
const urler = import.meta.env.VITE_API_HOST
const serverip = import.meta.env.VITE_SERVER_IP
</script>

<template>
  <el-card style="max-width: 100%" shadow="never">
    <template #header>
      <div class="card-header">
        <span>视频管理</span>
      </div>
    </template>
    <routerLink to="/addVideo"><el-button type="primary"><el-icon><UploadFilled /></el-icon>添加视频</el-button></routerLink><br><br>
    <el-table :data="videoData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="100px" align="center"/>
      <el-table-column align="center" label="封面(点击播放)" width="200px">
          <template #default="{ row }">
            <el-image
              :preview-teleported="true"
              :src="urler + row?.cover"
              style="width: 160px; height: 120px"
              @click="playVideo(row.video)"
            />
          </template>
      </el-table-column>
      <el-table-column prop="title" label="视频名称" min-width="200px" align="center"/>
      <el-table-column prop="video" label="视频地址" min-width="200px" align="center"/>
      <el-table-column label="是否可选集" min-width="200px" align="center">
        <template #default="{ row }">
          <el-tag type="primary" v-if="row.jis === 'true'">可以</el-tag>
          <el-tag type="primary" v-else>不可以</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="250px" align="center">
        <template #default="{ row }">
          <el-button type="danger" @click="delVideo(row.id)"><el-icon><Delete /></el-icon>删除</el-button>
          <el-button type="primary" @click="dialogVisible='true';input4=row.title; input5=row.cover; input6=row.video; id=row.id;"><el-icon><EditPen /></el-icon>修改信息</el-button>
          <el-button type="success" @click="dialogVisible2='true'; id1 = row.id; jisList = row.list"><el-icon><EditPen /></el-icon>添加集数</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <el-dialog v-model="dialogVisible" title="编辑视频信息" width="520" draggable align-center>
    <span>修改视频</span><br><br>
    <el-upload
      class="upload"
      drag
      multiple
      auto-upload
      :before-upload="handleChange"
      :on-success="handleSuccess"
      :on-error="handleError"
      :http-request="upload"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖动文件或 <em>点击上传</em>
      </div>
    </el-upload><br>
    <el-progress :percentage="progress" :stroke-width="15" striped /><br>
    <span>修改封面</span><br><br>
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadfm"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload><br>
    <div class="input"><el-input
      v-model="input4"
      style="width: 100%"
      placeholder="视频标题"
      clearable
    /></div><br>
    <div class="input"><el-input
      v-model="input5"
      style="width: 100%"
      placeholder="视频封面"
      clearable
    /></div><br>
    <div class="input"><el-input
      v-model="input6"
      style="width: 100%"
      placeholder="视频链接"
      clearable
    /></div><br>
    <span>是否有选集功能：</span><el-radio-group v-model="radio1">
      <el-radio value="1" size="large" border>true</el-radio>
      <el-radio value="2" size="large" border>false</el-radio>
    </el-radio-group><br><br>
    <div><el-button type="primary" @click="submit()"><el-icon><UploadFilled /></el-icon>提交信息</el-button></div>
  </el-dialog>
  <el-dialog v-model="dialogVisible1" title="视频播放" width="500" draggable @close="handleClose">
    <videoView :videoSrc="serverip + video" ref="VideoView" videoTitle="视频预览"></videoView>
  </el-dialog>
  <el-dialog v-model="dialogVisible2" title="集数管理" width="500" draggable>
    <el-tabs type="border-card">
      <el-tab-pane label="上传集数">
        <el-upload
          class="upload"
          drag
          multiple
          auto-upload
          :before-upload="handleChange"
          :on-success="handleSuccess"
          :on-error="handleError"
          :http-request="upload1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖动文件或 <em>点击上传</em>
          </div>
        </el-upload><br>
        <el-progress :percentage="progress" :stroke-width="15" striped /><br>
        <div class="input"><el-input
          v-model="input7"
          style="width: 100%"
          placeholder="集数标题"
          clearable
        /></div><br>
        <div class="input"><el-input
          v-model="input8"
          style="width: 100%"
          placeholder="集数链接"
          clearable
        /></div><br>
        <div class="button"><el-button type="primary" @click="submit1()"><el-icon><UploadFilled /></el-icon>提交上传</el-button></div>
      </el-tab-pane>
      <el-tab-pane label="集数管理">
        <el-table :data="jisList" border style="width: 100%">
          <el-table-column prop="id" label="ID" width="100px" align="center"/>
          <el-table-column prop="title" label="选集名称" width="180" align="center"/>
          <el-table-column prop="video" label="视频地址" width="180" align="center"/>
          <el-table-column label="操作" min-width="100px" align="center">
            <template #default="{ row }">
              <el-button type="danger" @click="delJis(row.id)"><el-icon><Delete /></el-icon>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>
<style>
:deep(.el-image) {
  img {
    object-fit: cover;
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 128px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 128px;
  text-align: center;
}
</style>
